package com.jxdinfo.mongodb.service.imp;

import com.jxdinfo.mongodb.dao.MemberReadHistoryRepository;
import com.jxdinfo.mongodb.model.MemberReadHistory;
import com.jxdinfo.mongodb.service.MemberReadHistoryService;
import com.jxdinfo.mongodb.util.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class MemberReadHistoryServiceImp implements MemberReadHistoryService {
    @Autowired
    private MemberReadHistoryRepository repository;

    @Override
    public String create(MemberReadHistory memberReadHistory) {
        memberReadHistory.setId(null);
        memberReadHistory.setCreateTime(new Date());
        MemberReadHistory entity = repository.save(memberReadHistory);
        if(entity != null){ // 成功
            return entity.getId();
        }else{
            return "";
        }
    }

    @Override
    public int delete(List<String> ids) {
        List<MemberReadHistory> list = new ArrayList<>();
        Iterable<MemberReadHistory> histories = repository.findAllById(ids);
        int count = 0;
        histories.forEach(memberReadHistory->{
            list.add(memberReadHistory);
        });
        repository.deleteAll(histories);
        return list.size();
    }

    @Override
    public int update(MemberReadHistory memberReadHistory) {
        MemberReadHistory save = repository.save(memberReadHistory);
        if(save != null){
            return 1;
        }else{
            return 0;
        }
    }

    @Override
    public List<MemberReadHistory> list(String memberId) {
        return repository.findByMemberIdOrderByCreateTimeDesc(memberId);
    }

    /**
     * 查询所有记录
     *
     * @return
     */
    @Override
    public List<MemberReadHistory> listAll() {
        return repository.findAll();
    }

    /**
     * 分页查询
     *
     * @param pageUtil
     * @return
     */
    @Override
    public Page<MemberReadHistory> listPage(PageUtil<MemberReadHistory> pageUtil) {
        MemberReadHistory memberReadHistory = pageUtil.getPageObj();
        ExampleMatcher exampleMatcher = ExampleMatcher.matching().withMatcher("memberNickName", ExampleMatcher.GenericPropertyMatchers.contains());
        Example<MemberReadHistory> example = Example.of(memberReadHistory, exampleMatcher);



        Pageable pageable = PageRequest.of(pageUtil.getCurrentPage(), pageUtil.getPageSize());
        return repository.findAll(example,pageable);
    }
}
